import router, { addRoutes } from './router'
import store from './store'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'


NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/screenboard', '/screendeck'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in
  const hasToken = getToken()

  // console.log(`hasToken: ${hasToken}`)
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({
        path: '/'
      })
      NProgress.done()
    } else {
      // 是否有用户信息

      /***** 引入用户接口以后的鉴权内容 ******/
      const hasUserInfo = store.getters.userId
      if (hasUserInfo) {
        next()
      } else {
        try {
          // get user info
          const { menus } = await store.dispatch('user/getInfo')

          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch('permission/generateRoutes', menus)

          // dynamically add accessible routes
          await addRoutes(accessRoutes)
          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({
            ...to,
            replace: true
          })
        } catch (error) {
          // remove token and go to login page to re-login
          // if()
          // next({
          //   ...to,
          //   replace: true
          // })
          // await store.dispatch('user/resetToken')
          ElMessage.error(error || 'Has Error')
          next(`/login`)
          NProgress.done()
        }
      }
    }

  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // need token
      next('/login')
    }

  }

})

router.afterEach((to) => {
  NProgress.done() // finish progress bar
})